package com.jb.repair.listener;

import android.content.Context;
import android.view.View;
import android.widget.AdapterView;


import com.jb.repair.adapter.TreeLedgerAdapter;
import com.jb.repair.model.LedgerModelTest;

import java.util.ArrayList;

/**
 * Created by SLF on 2015/12/23.
 */
public class TreeListener implements AdapterView.OnItemClickListener {

    private TreeLedgerAdapter leafAdapter;
    private Context context;
    private UpdateView updateView;

    public TreeListener(TreeLedgerAdapter leafAdapter, Context context, UpdateView updateView) {
        this.leafAdapter = leafAdapter;
        this.context = context;
        this.updateView = updateView;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        LedgerModelTest element = (LedgerModelTest) leafAdapter.getItem(position);
        ArrayList<LedgerModelTest> elements = leafAdapter.getElements();
        ArrayList<LedgerModelTest> elementsData = leafAdapter.getElementsData();

        if (!element.isHasChildren()) {
            //点击设备名称的处理事件
            updateView.update(element);
            return;
        }

        if (element.isExpanded()) {
            element.setExpanded(false);
            ArrayList<LedgerModelTest> elementsToDel = new ArrayList<LedgerModelTest>();
            for (int i = position + 1; i < elements.size(); i++) {
                if (element.getLevel() >= elements.get(i).getLevel())
                    break;
                elementsToDel.add(elements.get(i));
            }
            elements.removeAll(elementsToDel);
            leafAdapter.notifyDataSetChanged();
        } else {
            element.setExpanded(true);
            int i = 1;
            for (LedgerModelTest e : elementsData) {
                if (e.getParentId().equals(element.getLayerCode())) {
                    e.setExpanded(false);
                    elements.add(position + i, e);
                    i++;
                }
            }
            leafAdapter.notifyDataSetChanged();
        }
    }
    public static class UpdateView{
        public void update(LedgerModelTest ledgerModelTest){

        }
    }

}